package com.Servlet;

import com.dao.DaoFactory;
import com.entity.book;
import com.entity.chapter_examine;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;


@WebServlet(name = "uploadServlet", urlPatterns = "/uploadServlet")
public class uploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            response.setCharacterEncoding("UTF-8");
            System.out.println("-------------------------------------------------------------------");
            response.setContentType("text/html;charset=utf-8");
//            创建DiskFileItemFactory工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();

//            System.out.println("id:*/**/*//*/"+request.getParameter("id"));
//            System.out.println("host:*/**/*//*/"+request.getParameter("host"));


            String bookname = null;
            String author_name = null;
            String chapter_name = null;
//            设置文件缓存目录，如果该文件夹不存在则创建一个

//            download/${list1.author_name}/${list1.bookname}/${list1.chapter_name}

            File f = new File("D:\\fiction\\web\\download");
            if (!f.exists()) {
                f.mkdirs();
                System.out.println("创建文件夹");
            }
            factory.setRepository(f);
//            创建ServletFileUpload对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
//            设置字符编码
            fileUpload.setHeaderEncoding("utf-8");
//            解析request，将form表单的各个字段封装为FileItem对象
            List<FileItem> fileItems = fileUpload.parseRequest(request);
//            获取字符流
            PrintWriter writer = response.getWriter();
//            遍历List集合
            for (FileItem fileItem : fileItems) {
//                System.out.println("*##*"+fileItems);
//            判断是否为普通字段
                if (fileItem.isFormField()) {
//                    获取字段名称
                    System.out.println("普通字段：" + fileItems);
                    String name = fileItem.getFieldName();

                    if (name.equals("bookname")) {
//                        如果字段值不为空
                        if (!fileItem.getString().equals("")) {
                            String value = fileItem.getString("utf-8");
                            bookname = value;
                            writer.print("bookname：" + value + "<br />");
                        }
                    }
                    if (name.equals("author_name")) {
//                        如果字段值不为空
                        if (!fileItem.getString().equals("")) {
                            String value = fileItem.getString("utf-8");
                            author_name = value;
                            writer.print("author_name：" + value + "<br />");
                        }
                    }

                    System.out.println("bookname:" + bookname + "   author_name:" + author_name);
                } else {
                    System.out.println("文件字段：" + fileItems);
                    //获取上传的文件名
                    chapter_name = fileItem.getName();
//                    处理上传文件
                    if (chapter_name != null && chapter_name != "") {
                        writer.print("上传的文件名称是：" + chapter_name + "<br />");
                        System.out.println("filename:" + chapter_name);
//
                        String webpath = "/" + author_name + "/" + bookname + "/" + chapter_name;
                        System.out.println("webpath:" + webpath);
//                        创建文件路径

                        int edition = 1;


                        List<book> check = DaoFactory.getInstance().getbookDao().find(bookname, author_name);
                        if (check != null) {
                            for (int i = 0; i < check.size(); i++) {
                                int O = check.get(i).getChapter_no();
                                if ( O >= edition) {
                                    System.out.println("第" + i + "次：" + edition);
                                    edition = O + 1;
                                }
                            }
                        }

                        String path = "D:/fiction/web/download" + webpath;

                        System.out.println("path:" + path);
                        File file = new File(path);
                        //创建文件夹
                        file.getParentFile().mkdirs();
                        //创建文件
                        file.createNewFile();
                        //获取上传文件流
                        InputStream in = fileItem.getInputStream();
//                        使用 FileOutputStream打开服务器端的上传文件
                        FileOutputStream out = new FileOutputStream(file);
//                        流的对拷
                        byte[] bytes = new byte[1024];//每次读取一个字节
                        int len;
//                        开始读取上传文件的字节，并将其输出到服务器端的上传文件输出流中
                        while ((len = in.read(bytes)) > 0)
                            out.write(bytes, 0, len);
                        in.close();
                        out.close();
                        fileItem.delete();


                        chapter_examine box = new chapter_examine();
                        box.setBookname(bookname);
                        box.setChapter_name(chapter_name);
                        box.setAuthor_name(author_name);
                        box.setChapter_no(edition);
                        box.setAddress(path);

                        DaoFactory.getInstance().getchapter_examineDao().add(box);

                        writer.print("文件上传成功！，等待审核");

                    }
                }


            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}